<template>
  <div class="midify-pwd-container">
    <Heads title="设置" :right-flag="false"></Heads>

    <van-form validate-first @failed="onModifyPwdFailed" @submit="onModifyPwdSubmit">
      <!-- 通过 pattern 进行正则校验 -->
      <van-cell-group class="mt">
        <van-field
          v-model="oldpassword"
          type="password"
          name="oldpassword"
          label="原密码"
          placeholder="请输入原始密码"
        />
      </van-cell-group>
      <!-- 通过 validator 进行函数校验 -->
      <van-cell-group class="mt">
        <van-field
          v-model="newpassword"
          type="password"
          name="newpassword"
          label="新密码"
          placeholder="请输入新密码"
          :rules="[{ validator, message: '请输入6到10位的数字或字母' }]"
        />
      </van-cell-group>
      <!-- 通过 validator 进行异步函数校验 -->
      <van-cell-group class="mt">
        <van-field
          v-model="confirmpassword"
          type="password"
          name="confirmpassword"
          label="确认密码"
          placeholder="请再次输入新密码"
          :rules="[{ validator: asyncValidator, message: '两次输入密码不一致' }]"
        />
      </van-cell-group>
      <!-- 验证码 - canvas -->
      <van-cell-group class="mt">
        <van-cell>
          <!-- 左边输入框 -->
          <template #title>
            <van-field
              v-model="verificationcode"
              name="verificationcode"
              placeholder="请输入验证码"
              @keyup.enter.native="onModifyPwdSubmit"
            ></van-field>
          </template>
          <!-- 右边canvas画布 -->
          <template #default>
            <div id="v_container"></div>
          </template>
        </van-cell>
      </van-cell-group>
      <!-- 确认 submit -->
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { GVerify } from "@/utils/verifyCode.js";
import { post } from "@/utils/axios";
import { mapState, mapMutations, mapActions } from "vuex";
import Vue from "vue";
import {
  Field,
  Image as VanImage,
  Cell,
  CellGroup,
  Dialog,
  Form,
  Toast,
  Button
} from "vant";

Vue.use(Field)
  .use(VanImage)
  .use(Cell)
  .use(CellGroup)
  .use(Dialog)
  .use(Form)
  .use(Toast)
  .use(Button);
export default {
  data() {
    return {
      oldpassword: "",
      newpassword: "",
      confirmpassword: "",
      verificationcode: "",
      pattern: /^[a-zA-Z0-9][a-zA-Z0-9]{5,9}$/,
      verifyCode: null
    };
  },
  computed: {
    ...mapState("userModule", ["userinfo", "token"])
  },
  methods: {
    ...mapMutations("footerModule", ["FOOTERSHOW"]),
    /********************* ------------ *********************/
    /********************* 修改密码start *********************/
    /********************* ------------ *********************/
    /**
     * errorInfo: { values: object, errors: object[] }
     */
    onModifyPwdFailed(errorInfo) {
      console.log("检验错误", errorInfo.errors);
    },
    /**
     * values: object
     */
    onModifyPwdSubmit(values) {
      Toast.loading("验证中...");
      //  通过在data中定义的verifyCode对象的validate()方法，如果输入正确返回true 错误返回 false
      let verifyFlag = this.verifyCode.validate(this.verificationcode);
      // console.log(this.verifyCode.validate(this.verificationcode), this.verificationcode)
      if (!verifyFlag) {
        Toast.clear();
        Toast({
          message: "验证码输入不正确",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
      } else {
        post({
          url: "/hybrid/uni/modify-pwd",
          data: {
            oldPassword: values.oldpassword,
            password: values.confirmpassword
          }
        }).then(res => {
          if (res.status === 0) {
            Toast.clear();
            // 不清token了吧, 麻烦
            Toast({
              message: "修改成功",
              closeOnClick: true,
              forbidClick: true,
              duration: 500
            });
            this.$router.replace({
              name: "Home"
            });
          } else {
            Toast({
              message: res.msg,
              closeOnClick: true,
              forbidClick: true,
              duration: 500
            });
          }
        });
      }
    },

    /**
     * 校验函数返回 true 表示校验通过，false 表示不通过
     */
    validator(val) {
      return this.pattern.test(val);
    },
    /**
     * 异步校验函数返回 Promise(通过resolve的状态来校验)
     * 此处不用:下方还有验证码,体验不佳
     */
    // asyncValidator(val) {
    //   return new Promise(resolve => {
    //     Toast.loading("验证中...");
    //     setTimeout(() => {
    //       Toast.clear();
    //       resolve(this.pattern.test(val));
    //     }, 1000);
    //   });
    // }
    asyncValidator(val) {
      if (val === this.newpassword) {
        return true;
      } else {
        return false;
      }
    }
  },
  mounted() {
    this.FOOTERSHOW(false);
    // 实例化
    this.verifyCode = new GVerify("v_container");
  },
  destroyed() {
    this.FOOTERSHOW(true);
  }
};
</script>

<style lang="scss" scoped>
.midify-pwd-container {
  .mt {
    margin: 10px;
    border-radius: 10px;
    overflow: hidden;
  }
}
</style>
